<template>
  <div style="display:flex;width:100%; margin:0;padding:0;">
    <div style="flex-grow:8;flex-wrap: wrap;margin:0;padding:0;">
      <codemirror
        v-model="code"
        placeholder="Coding..."
        :style="{ height: '100vh' ,' text-align':'left', 'font-size':'20px'}"
        :autofocus="true"
        :indent-with-tab="true"
        :tab-size="4"
        :extensions="extensions"
        @ready="handleReady"
        @change="log('change', $event)"
        @focus="log('focus', $event)"
        @blur="log('blur', $event)"
      />
    </div>
    <div style="flex-basis: 400px;">
      <div style="margin-top: 25px;">
        <el-button type="success" round @click="codeRun">
          <el-icon size="20"><CaretRight /></el-icon>
          运行
        </el-button>

        <el-switch
          v-model="theme"
          class="mt-2"
          style="margin-left: 24px"
          inline-prompt
          active-icon="Moon"
          inactive-icon="Sunny"
          @change="themeChange"
        />
      </div>
      <div>
       
      </div>
      
      <el-divider />
      {{ result }}
    </div>
  </div>

  <el-drawer
    title="运行结果"
    v-model="drawer"
    direction="ttb"
    size="600"
    destroy-on-close
  >
    <el-table :data="tableData" empty-text="无数据" border style="width: 100%">
      <el-table-column :prop="item" :label="item" v-for="(item, index) in header" :key="index"> </el-table-column>
    </el-table>
  </el-drawer>
</template>

<script>
import { getAction, postAction } from '@/util/request.js'
import { trim } from '@/util/stringutils.js'
import { defineComponent, ref, reactive, shallowRef } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { sql } from '@codemirror/lang-sql'
import { oneDark } from '@codemirror/theme-one-dark'
export default defineComponent({
  components: {
    Codemirror,
  },
  setup() {
    const theme = ref(true)
    const themeChange = (t)=>{
      if(t) {
        extensions.value = [sql(), oneDark]
      } else {
        extensions.value = [sql()]
      }
    }
    //默认显示代码
    const code = ref(`insert into user(name) values('小港')`)
    let extensions = ref([sql(), oneDark])

    // Codemirror EditorView instance ref
    const view = shallowRef()
    const handleReady = (payload) => {
      view.value = payload.view
    }

    // Status is available at all times via Codemirror EditorView
    const getCodemirrorStates = () => {
      const state = view.value.state
      const ranges = state.selection.ranges
      const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
      const cursor = ranges[0].anchor
      const length = state.doc.length
      const lines = state.doc.lines
        // more state info ...
        // return ...
    }
    const url = "/code/sql/execute"
    let result = ref('')
    let header = ref([])
    let tableData = ref([])
    let drawer = ref(false)
    const codeRun = ()=> {
      result.value = '运行中，请等待...'

      postAction(
        url,
        {code: trim(code.value)}
      ).then(res=>{
        if(res.code == 1) {
          if(res.data.code == 0) {
            result.value = res.data.msg
          }
            
          let timer
          timer = setInterval(function() {
            getAction(
              '/execute/result/get/' + res.data.number, {}
            ).then(r=>{
              if(r.code == 1) {
                if(r.data.result == 1) {
                  clearInterval(timer)
                    
                  //判断操作类型
                  if(r.data.data.sqlType == 'SELECT') {
                    header.value = r.data.data.header
                    tableData.value = r.data.data.list
                    result.value = ''
                    drawer.value = true
                  }
                  if(r.data.data.sqlType == 'INSERT') {
                    if(r.data.data.count == 1) {
                      result.value = '添加成功'
                    }
                  }
                  if(r.data.data.sqlType == 'UPDATE') {
                    if(r.data.data.count == 1) {
                      result.value = '更新成功'
                    }
                  }
                  if(r.data.data.sqlType == 'DELETE') {
                    if(r.data.data.count == 1) {
                      result.value = '删除成功'
                    }
                  }
                }

                if(r.data.result == 0) {
                  clearInterval(timer)
                  result.value = r.data.msg
                }
              }
              if(r.code == 2) {
                //继续循环
              }
            })
          }, 600)
        }

        if(res.code == 2) {
          result.value = '运行异常:' + res.msg
        }
          
      })

    }
    return {
      code,
      extensions,
      handleReady,
      codeRun,
      log: console.log,
      result,
      header,
      tableData,
      theme,
      themeChange,
      drawer
    }
  }
})
</script>